package com.ccteam.admin.viewmodels.login

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.hutool.crypto.asymmetric.KeyType
import cn.hutool.crypto.asymmetric.RSA
import com.ccteam.admin.core.AdminCore
import com.ccteam.admin.repositories.BaseAdminRepository
import com.ccteam.admin.utils.ErrorMessage
import com.ccteam.admin.utils.Event
import com.ccteam.admin.utils.LoadMessage
import com.ccteam.admin.vo.Resource
import com.ccteam.network.ApiError
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/4/6
 */
@HiltViewModel
class LoginViewModel @Inject constructor(
    private val adminCore: AdminCore,
    private val baseAdminRepository: BaseAdminRepository
): ViewModel() {

    private val _loadMessage = MutableLiveData<Event<LoadMessage>>()
    val loadMessage: LiveData<Event<LoadMessage>> get() = _loadMessage

    private val _isLogin = MutableLiveData<Boolean>()
    val isLogin: LiveData<Boolean> get() = _isLogin

    private var loginStatusJob: Job? = null
    init {
        loginStatusJob = viewModelScope.launch {
            adminCore.isLogin.collectLatest {
                _isLogin.value = it
            }
        }
    }

    /**
     * 管理员登录
     */
    fun login(adminName: String,password: String){
        if(adminName.isEmpty() || password.isEmpty()){
            _loadMessage.value = Event(LoadMessage.Error(ErrorMessage(ApiError.unknownCode,"账号密码为空")))
            return
        }
        _loadMessage.value = Event(LoadMessage.Loading)


        viewModelScope.launch {

            val rsaResult = baseAdminRepository.getPublicRSAKey()
            if(rsaResult !is Resource.Success || rsaResult.data.isNullOrEmpty()){
                _loadMessage.value = Event(LoadMessage.Error(ErrorMessage(ApiError.serverErrorCode,rsaResult.message)))
                return@launch
            }

            // 将密码RSA加密
            val rsa = RSA(null,rsaResult.data)
            val rsaPassword = rsa.encryptBcd(password, KeyType.PublicKey)

            val result = baseAdminRepository.loginAdmin(adminName,rsaPassword)

            if(result is Resource.Success){
                adminCore.login(result.data!!.userId,result.data.tokenValue,adminName)
                _loadMessage.value = Event(LoadMessage.Success)
            } else {
                _loadMessage.value = Event(LoadMessage.Error(ErrorMessage(ApiError.serverErrorCode,result.message)))
            }
        }
    }

    override fun onCleared() {
        super.onCleared()

        loginStatusJob?.cancel()
    }
}